﻿using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Eagles.Application.Model.Meeting.Model;
using Eagles.Application.Model.Meeting.Requset;
using Eagles.Application.Model.Meeting.Response;
using Eagles.Application.Model.News.Requset;
using Eagles.Base;
using Eagles.Base.Cache;
using Eagles.DomainService.Model.News;
using Eagles.DomainService.Model.Score;
using Eagles.DomainService.Model.User;
using Eagles.Interface.Core;
using Eagles.Interface.DataAccess;

namespace Eagles.DomainService.Core
{
    public class MettingHandler : IMettingHandler
    {
        private readonly IMettingDataAccess dataAccess;
        private readonly IAuditDataAccess auditdataAccess;
        private readonly INewsDataAccess NewdataAccess;
        private readonly ICacheHelper cacheHelper;

        private readonly IPartyMemberDataAccess UserdataAccess;
        public MettingHandler(IMettingDataAccess dataAccess, INewsDataAccess newdataAccess, IPartyMemberDataAccess userdataAccess, IAuditDataAccess auditdataAccess, ICacheHelper cacheHelper)
        {
            this.dataAccess = dataAccess;
            NewdataAccess = newdataAccess;
            UserdataAccess = userdataAccess;
            this.auditdataAccess = auditdataAccess;
            this.cacheHelper = cacheHelper;
        }

        public ImportMeetingResponse ImportMeetUserInfoRequset(ImportMeetUserInfoRequset requset)
        {
            var token = cacheHelper.GetData<TbUserToken>(requset.Token);
            var response = new ImportMeetingResponse { ImportUsersResult = new List<MeetUser>() };
       
            var list = new List<string>();

            var news = NewdataAccess.GetNewsDetail(new GetNewDetailRequset()
            {
                NewsId = requset.MeetingId
            });

            if (news.NewsType != 1)
            {
                throw new TransactionException("M09");
            }

            if (news.Status != "0")
            {
                throw new TransactionException("M13");
            }

            foreach (var md in requset.List)
            {
                if (md.MeetUserPhone.Length!=11)
                {
                    md.ErrorMessage = "手机号格式错误！";
                    response.ImportUsersResult.Add(md);
                    continue;
                }

                list.Add(md.MeetUserPhone);
            }

            if (list.Count == 0)
            {

                response.ImportStart = 0;
                return response;
            }

            List<TbUserInfo> user = dataAccess.GetUserInfoByPhone(list);

            if (user.Count == 0)
            {
               throw new TransactionException("M14");
            }

            //remove old data
            var removeResult = dataAccess.RemoveMeetingUser(requset.MeetingId);
            var userinfo = user.Select(x => new TbMeetingUser()
            {
                BranchId = x.BranchId,
                NewsId = requset.MeetingId,
                OrgId = x.OrgId,
                UserId = x.UserId
            }).ToList();


            if (dataAccess.CreateUserInfo(userinfo) <= 0)
            {
                response.ImportUsersResult.AddRange(userinfo.Select(x => new MeetUser()
                {
                    MeetUserName = user.FirstOrDefault(f => f.UserId == x.UserId)?.Name,
                    MeetUserPhone = user.FirstOrDefault(f => f.UserId == x.UserId)?.Phone
                }));
            }
            else
            {

                var score = auditdataAccess.GetScoreSet(token.OrgId, 0, 30);
                var users= UserdataAccess.GetUserInfoList(userinfo.Select(x => x.UserId).ToList());

                List<TbUserScoreTrace> ls = new List<TbUserScoreTrace>();
                foreach (var us in userinfo)
                {
                    var userDetail = users.FirstOrDefault(x => x.UserId == us.UserId);

                    ls.Add(new TbUserScoreTrace()
                    {
                        Comment = "参加会议'" + news.Title + "'增加积分",
                        UserId = us.UserId,
                        Score = score,
                        RewardsType = "30",
                        OrgId = token.OrgId,
                        OriScore = userDetail?.Score ?? 0,
                        //Content = "参加会议'" + news.Title + "'增加积分"
                    });
                }

                auditdataAccess.SetUserScore(score, userinfo.Select(x => x.UserId).ToList());

                auditdataAccess.UserScoreTrace(ls);



            }

            response.ImportStart = 1;

            if (response.ImportUsersResult.Count > 0)
            {
                response.ImportStart = 2;
            }

            return response;

        }

        public GetMeetingResponse GetMettingUsers(GetMeetingRequest requset)
        {
            var response = new GetMeetingResponse
            {
                TotalCount = 0,
            };
            List<TbMeetingUser> list = dataAccess.GetMettingUsers(requset) ??
                                       new List<TbMeetingUser>();

            if (list.Count == 0) throw new TransactionException("M01");

            List<TbNews> news = NewdataAccess.GetNewsList(list.Select(x => x.NewsId).ToList());

            //  List<TbUserInfo> userInfo = UserdataAccess.GetUserInfoList(list.Select(x => x.UserId).ToList());
            // var orginfo = OrgdataAccess.GetOrganizationList(list.Select(x => x.OrgId).ToList());

            //组装返回数据
            response.List = list.GroupBy(g => new { g.NewsId }).Select(f => new Meeting
            {
                MeetingId = f.Key.NewsId,
                MeetingInitiator = news.FirstOrDefault(x => x.NewsId == f.Key.NewsId)?.Author,
                MeetingName = news.FirstOrDefault(x => x.NewsId == f.Key.NewsId)?.Title,
                Participants =
                      UserdataAccess
                          .GetUserInfoList(list.Where(x => x.NewsId == f.Key.NewsId).Select(x => x.UserId).ToList())
                          .Select(x => new MeetingUser()
                          {

                              Phone = x.Phone,
                              UserName = x.Name
                          }).ToList()
            }).ToList();

            response.TotalCount = response.List[0].Participants.Count;


            //新闻名字条件筛选
            if (!string.IsNullOrWhiteSpace(requset.MeetingName))
            {

                response.List = response.List.Where(x => x.MeetingName == requset.MeetingName).ToList();

            }

            return response;

        }
    }
}
